﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMS.Core.General;
using CMS.Core.Types;
using CMS.Core;
using CMS.Web.Filters;
using CMS.Web.Areas.Admin.Models;

namespace CMS.Web.Areas.Admin.Controllers
{
    [AdminAuthorize]
    public class AdminController : Controller
    {
        // GET: Admin/Admin

        //admins管理类
        AdministratorManager adminManager = new AdministratorManager();

        /// <summary>
        /// 登录视图
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ViewResult Login()
        {
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginInfo">登录信息</param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(LoginViewModel loginInfo)
        {
            if(ModelState.IsValid)
            {
                string password = Security.Sha256(loginInfo.Password);
                var response = adminManager.Verify(loginInfo.Accounts, password);

                if(response.Code == 1)
                {
                    var admin = adminManager.Find(loginInfo.Accounts);
                    Session.Add("AdminID", admin.AdministratorID);
                    Session.Add("Accounts", admin.Accounts);
                    admin.LoginIP = Request.UserHostAddress;
                    admin.LoginTime = DateTime.Now;
                    adminManager.Update(admin);
                    return RedirectToAction("Index", "Home");
                }
                else if(response.Code == 0)
                {
                    ModelState.AddModelError("Accounts", response.Message);                  
                }
                else
                {
                    ModelState.AddModelError("Password", response.Message);
                }
            }

            return View(loginInfo);
        }

        /// <summary>
        /// 注销登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            Session.Clear();
            return View("Login");
        }


        /// <summary>
        /// 插入一个账号
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Create()
        {
            Administrator user = new Administrator()
            {
                Accounts = "Ywshmily",
                Password = Security.Sha256("123456"),
                CreateTime = DateTime.Now
            };
            adminManager.Add(user);

            return Content("Create success");
        }
 
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public ViewResult Index()
        {
            return View();
        }

        /// <summary>
        /// 管理员列表
        /// </summary>
        /// <returns>管理员Json数据</returns>
        public JsonResult ListJson()
        {
            return Json(adminManager.FindList(), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 增加管理员账号分部视图
        /// </summary>
        /// <returns></returns>
        public PartialViewResult AddAdmin()
        {
            return PartialView();
        }

        /// <summary>
        /// 添加管理员动作
        /// </summary>
        /// <param name="adminInfo">管理员信息</param>
        /// <returns>Respon类响应信息</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult AddAdminJson(AddAdminViewModel adminInfo)
        {
            CMS.Core.Types.Response response = new Response();

            if(ModelState.IsValid)
            {
                if(adminManager.HasAccounts(adminInfo.Accounts))
                {
                    response.Code = 0;
                    response.Message = "该账号已经存在";
                }
                else
                {
                    Administrator admin = new Administrator()
                    {
                        Accounts = adminInfo.Accounts,
                        Password = Security.Sha256(adminInfo.Password),
                        CreateTime = DateTime.Now
                    };

                    response = adminManager.Add(admin);
                    response.Message = adminInfo.Accounts.ToString() +  "添加成功";
                }
            }
            else
            {
                response.Message = General.GetModelErrorString(ModelState);
                response.Code = 2;
            }

            return Json(response, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <param name="idList">准备删除的管理员账号ID</param>
        /// <returns>0--删除失败, 1--全部删除, 2--部分删除</returns>
        [HttpPost]
        public JsonResult DeleteJson(List<int> idList)
        {
            int currentAdminID = Convert.ToInt32(Session["AdminID"]);
            int totalDel = idList.Count;
            Response response = new Response() { Code = 0 };

            if(idList.Contains(currentAdminID))
            {
                idList.Remove(currentAdminID);
                totalDel--;
            }

            if(totalDel > 0)
            {
                response = adminManager.Delete(idList);
                
                if(response.Code == 1 && response.Data == totalDel)
                {
                    response.Code = 1;
                    response.Message = "总共提交" + totalDel + "个账号, 已经全部删除";
                }
                else if(response.Code == 1)
                {
                    response.Code = 2;
                    response.Message = "总共提交" + totalDel + "个账号, 实际删除" + response.Data + "个账号. 原因:当前登陆账号不能被删除;";
                }
                else if(response.Code == 2 )
                {
                    response.Code = 2;
                    response.Message = "总共提交" + totalDel + "个账号, 实际删除" + response.Data + "个账号";
                }           
            }

            return Json(response, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id">账号ID</param>
        /// <returns>Response类 0--重置失败, 1--重置成功</returns>
        [HttpPost]
        public JsonResult ResetPassword(int id)
        {
            string password = "default";
            string encryptPassword = Security.Sha256(password);
            var response = adminManager.ChangePassword(id, encryptPassword);

            if(response.Code == 1)
            {
                response.Message = "密码重置为: " + password;
            }
            else
            {
                response.Message = "重置失败,原因：" + response.Message;
            }

            return Json(response, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 我的信息
        /// </summary>
        /// <returns></returns>
        public ViewResult MyInfo()
        {
            int id = Convert.ToInt32(Session["AdminId"]);
            var admin = adminManager.Find(id);

            return View(admin);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult MyInfo(Administrator admin)
        {
            var adminTemp = adminManager.Find(admin.AdministratorID);
            var password = Security.Sha256(admin.Password);
            if(adminTemp.Password != admin.Password)
            {
                var resp = adminManager.ChangePassword(admin.AdministratorID, password);
                if(resp.Code == 1)
                {
                     ViewBag.Message = "<div class=\"alert alert-success\" role=\"alert\"><span class=\"glyphicon glyphicon-ok\"></span>修改密码成功！</div>";
                }
                else
                {
                    ViewBag.Message = "<div class=\"alert alert-danger\" role=\"alert\"><span class=\"glyphicon glyphicon-remove\"></span>修改密码失败！</div>";
                }
            }
            else
            {
                ViewBag.Message = "<div class=\"alert alert-danger\" role=\"alert\"><span class=\"glyphicon glyphicon-remove\"></span>上传数据错误</div>";
            }
            return View(adminTemp);
        }
    }
}